package com.zyk.binary;

/**
 * @author zhangsan
 * @date 2021/6/13 12:01
 */
public class Operation {

    public static int add(int a, int b) {
        int sum = a;
        while (b != 0) {
            sum = a ^ b;        // 无进位相加
            b = (a & b) << 1;   // 进位相加
            a = sum;
        }
        return sum;
    }

    // a + (-b)
    public static int minus(int a, int b) {
//        return add(a, (~b + 1));
        return add(a, add(~b, 1));
    }

    // 跟10进制, 相乘一样的算.   二进制写的优雅点
    public static int multiply(int a, int b) {
        int res = (b & 1) == 0 ? 0 : a;
        while (b != 0) {
            b >>= 1;
            a <<= 1;
//            res += (b & 1) == 0 ? 0 : a;
            if((b & 1) == 1)
                res = add(res, a);
        }
        return res;
    }

    public static int divide(int dividend, int divisor) {
        if (dividend < divisor) return 0;
        int ans = 1;
        int step = divisor << 1;
        while (dividend > step) {
            step <<= 1;
            ans <<= 1;
        }
        return ans + divide(dividend - (step >> 1), divisor);
    }


    public static int add2(int a, int b) {
        return a + b;
    }

    public static int minus2(int a, int b) {
        return a - b;
    }

    public static int multiply2(int a, int b) {
        return a * b;
    }

    public static int divide2(int a, int b) {
        return a / b;
    }


    public static void main(String[] args) {
        int a = 212133,
                b = 3213;
        System.out.println(add(a, b));
        System.out.println(add2(a, b));;
        System.out.println(minus(a, b));
        System.out.println(minus2(a, b));
        System.out.println(multiply(a, b));
        System.out.println(multiply2(a, b));
        System.out.println(divide(a, b));
        System.out.println(divide2(a, b));
    }

}
